package com.oschina.bottle.mysql.servlet;

import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import com.oschina.bottle.mysql.MysqlAdminProperties;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * druid监控配置
 *
 * @author <a href="mailto:zhongchao@gegejia.com">zhong</a>
 * @version 1.0 2016/11/22
 * @since 1.0
 */
@Configuration
@EnableConfigurationProperties(MysqlAdminProperties.class)
public class DruidServletConfiguration
{
    private static final Logger logger = LoggerFactory.getLogger(DruidServletConfiguration.class);

    @Autowired
    private MysqlAdminProperties mysqlAdminProperties;

    @Bean
    public ServletRegistrationBean druidServlet() {
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean();
        servletRegistrationBean.setServlet(new StatViewServlet());
        servletRegistrationBean.addUrlMappings("/druid/*");
        Map<String, String> initParams = new HashMap<>();

        String username = "admin";
        if(StringUtils.hasText(mysqlAdminProperties.getUsername())){
            initParams.put("loginUsername", mysqlAdminProperties.getUsername());
        } else {
            initParams.put("loginUsername", username);
        }

        String password = "admin";
        if(StringUtils.hasText(mysqlAdminProperties.getPassword())){
            initParams.put("loginPassword", mysqlAdminProperties.getPassword());
        } else {
            initParams.put("loginPassword", password);
        }

        initParams.put("resetEnable", "false");
        initParams.put("allow", "");

        servletRegistrationBean.setInitParameters(initParams);
        return servletRegistrationBean;
    }

    @Bean
    public FilterRegistrationBean filterRegistrationBean() {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        filterRegistrationBean.setFilter(new WebStatFilter());
        filterRegistrationBean.addUrlPatterns("/*");
        filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        return filterRegistrationBean;
    }


}
